package com.feihong.txgw.ui.activity.order;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.inter.contract.pay.IPayContract;
import com.feihong.txgw.json.pay.JiFenParser;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.RefreshOrder;
import com.feihong.txgw.tx_precenter.PayMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.ToastUtils;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.tsy.sdk.pay.weixin.WXPay;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
/**
 * Created by Sabirjan on 2017/7/6.
 * TXGWApp.
 * 飞宏电子
 * 统一付款页面
 */

public class PayActivity extends BaseMVPCompateActivity<IPayContract.AbPayMainPrecenter> implements IPayContract.IPayMainView {

    /**
     * handle_kk_notify 开卡
     * handle_hf_notify 话费
     * handle_ll_notify   流量
     * handle_zd_notify  终端
     * 四种订单的参数
     */

    /**
     * 购买产品
     */
    public static final int PAY_TYPE_PRODUCT = 4;
    /**
     * 开卡
     */
    public static final int PAY_TYPE_KAIKA = 3;
    /**
     * 话费充值
     */
    public static final int PAY_TYPE_PHONE_RECHARGE = 1;
    /**
     * 流量充值
     */
    public static final int PAY_TYPE_PHONE_GPRS = 2;


    public static final String INTENT_GOODS_ID = "sku_id";
    /**
     * 支付类型 （购买产品,开卡,话费） 必填
     */
    public static final String INTENT_PAY_TYPE = "paytype";
    /**
     * 支付的内容, 比如： 充值话费20元 可选
     */
    public static final String INTENT_TITLE = "paytitle";
    /**
     * 需要支付的金额 必填
     */
    public static final String INTENT_PRICE = "payprice";
    /**
     * v
     */
    public static final String INTENT_ORDER_ID = "payorderid";
    /**
     * 订单介绍的详细信息 可选
     */
    public static final String INTENT_DES = "paydes";
    /**
     * 来源 第一次支付还是 再次支付
     */
    public static final String INTENT_FROM = "from";

    @BindView(R.id.txt_mony_title)
    TextView txtMonyTitle;
    @BindView(R.id.txt_mony)
    TextView txtMony;

    @BindView(R.id.txt_monyDes_title)
    TextView txtMonyDesTitle;
    @BindView(R.id.txt_monyDes)
    TextView txtMonyDes;


    @BindView(R.id.txt_gold_title)
    TextView txtGoldTitle;
    @BindView(R.id.txt_gold_des)
    TextView txtGoldDes;
    @BindView(R.id.spinner)
    MaterialSpinner spinner;
    @BindView(R.id.img_wechaticon)
    ImageView imgWechaticon;
    @BindView(R.id.txt_wechat_title)
    TextView txtWechatTitle;
    @BindView(R.id.lay_wechatpay)
    RelativeLayout layWechatpay;
    @BindView(R.id.img_aliicon)
    ImageView imgAliicon;
    @BindView(R.id.txt_ali_title)
    TextView txtAliTitle;
    @BindView(R.id.lay_alipay)
    RelativeLayout layAlipay;
    @BindView(R.id.btn_pay)
    Button btnPay;

    @BindView(R.id.checkbox_jifen)
    CheckBox checkbox_jifen;

    @BindView(R.id.txt_jifen_mony)
    TextView txt_jifen_mony;


    private String orderID = "";
    private String handle_notify = "";
    private float price = 0.0f;
    private String title = "";
    private int payType = 0;
    /**
     * 积分信息
     */
    private JiFenParser jifenParser;
    /**
     * 积分列表
     */
    JiFenParser.DataBean.JifeninfoBean jifeninfo;
    private int jifen_selectedIndex = -1;
    private String use_point = "";
    /**
     * 1 第一次支付  2 再次支付
     */
    private int from = 1;

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_pay;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        setPageTitle("订单支付");
        setBackButtonFinish();
        //默认  false
        btnPay.setEnabled(false);
        btnPay.setText("确认支付 " + price + "元");
    }


    private void bindViewData() {
        txtMony.setText("¥ " + price + "");
        ArrayList<String> dataset = new ArrayList<>();
        btnPay.setEnabled(true);
        if (jifenParser == null || jifenParser.getData() == null ||
                jifenParser.getData().getJifeninfo() == null ||
                jifenParser.getData().getJifeninfo().getPoint_info() == null || jifenParser.getData().getJifeninfo().getCan_use() == null) {
            findViewById(R.id.lay_jifenselect).setVisibility(View.GONE);
            checkbox_jifen.setBackgroundResource(R.mipmap.delivery_adr_setting_close);
            btnPay.setText("确认支付 " + price + " 元");
            String jifenDes = "可用%s，待返%s，冻结%s积分";
            jifenDes = String.format(jifenDes, "0", "0", "0");
            txtGoldDes.setText(jifenDes);
            use_point = "";
            checkbox_jifen.setEnabled(false);

            return;
        }
        if (jifenParser.getData().getJifeninfo().getCan_use().size() > 0) {
            jifeninfo = jifenParser.getData().getJifeninfo();
            for (JiFenParser.DataBean.JifeninfoBean.CanUseBean item : jifeninfo.getCan_use()) {
                dataset.add(item.getPoint() + "");
            }
            if (dataset.size() == 1) {
                dataset.addAll(dataset);
            }
            spinner.setItems(dataset);

            spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {

                @Override
                public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                    setJifenAndPrice(position);
                }
            });

            if (jifeninfo.getPoint_info() != null && jifeninfo.getPoint_info().getHuode() != null && jifeninfo.getPoint_info().getDaifan() != null) {

                checkbox_jifen.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        LogUtils.i("--" + buttonView.isChecked() + "  ");
                        if (isChecked) {
                            findViewById(R.id.lay_jifenselect).setVisibility(View.VISIBLE);
                            checkbox_jifen.setBackgroundResource(R.mipmap.delivery_adr_setting_open);
                            if (jifen_selectedIndex < 0) {
                                jifen_selectedIndex = 0;
                            }
                            setJifenAndPrice(jifen_selectedIndex);
                        } else {
                            findViewById(R.id.lay_jifenselect).setVisibility(View.GONE);
                            checkbox_jifen.setBackgroundResource(R.mipmap.delivery_adr_setting_close);
                            btnPay.setText("确认支付 " + price + " 元");
                            use_point = "0";
                        }
                    }
                });
                findViewById(R.id.jifenInfo).setVisibility(View.VISIBLE);
                findViewById(R.id.lay_jifenselect).setVisibility(View.GONE);
                //默认 false
                checkbox_jifen.setChecked(false);
                txtGoldDes.setText("总积分:" + jifeninfo.getPoint_info().getHuode() + "   待返积分:" + jifeninfo.getPoint_info().getDaifan());
                checkbox_jifen.setBackgroundResource(R.mipmap.delivery_adr_setting_close);
                btnPay.setText("确认支付 " + price + " 元");
                use_point = "0";
            }
        }
    }

    private void setJifenAndPrice(int position) {
        try {

            if (jifeninfo.getCan_use().size() == 1 && position == 1) {
                position = position - 1;
            }

            if (position < jifeninfo.getCan_use().size()) {
                float jifenprice = Float.parseFloat(jifeninfo.getCan_use().get(position).getPrice());
                use_point = jifeninfo.getCan_use().get(position).getPoint();


                DecimalFormat df = new DecimalFormat("######0.00");
                String p = df.format(jifenprice);
                txt_jifen_mony.setText("¥ " + p);
                jifen_selectedIndex = position;
                float newPrice = price - jifenprice;

                if (newPrice < 0) {
                    newPrice = 0;
                }
                p = df.format(newPrice);
                btnPay.setText("确认支付 " + p + " 元");
            } else {
                findViewById(R.id.jifenInfo).setVisibility(View.GONE);
                use_point = "0";
                jifen_selectedIndex = -1;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            findViewById(R.id.lay_jifenselect).setVisibility(View.GONE);
            btnPay.setText("确认支付 " + price + " 元");
            use_point = "";
            checkbox_jifen.setEnabled(false);
            showSystemToast("无法转换积分数据！");
            findViewById(R.id.jifenInfo).setVisibility(View.GONE);
        }
    }

    @Override
    public void bindData() {
        super.bindData();
        orderID = getIntent().getStringExtra(INTENT_ORDER_ID);
        payType = getIntent().getIntExtra(INTENT_PAY_TYPE, 0);
        // 价格
        title = getIntent().getStringExtra(INTENT_TITLE);
        from = getIntent().getIntExtra(INTENT_FROM, 1);
        if (!TextUtils.isEmpty(orderID)) {
            txtMony.setText("¥ " + price + "");

        } else {
            ToastUtils.getInstance().showShortToast("订单号为空");
            finish();
        }

        String tempTitle = "";
        switch (payType) {
            case PAY_TYPE_KAIKA:
                handle_notify = "handle_kk_notify";
                tempTitle = "手机开卡订单";
                break;
            case PAY_TYPE_PHONE_GPRS:
                handle_notify = "handle_ll_notify";
                tempTitle = "购买流量订单";
                break;
            case PAY_TYPE_PHONE_RECHARGE:
                handle_notify = "handle_hf_notify";
                tempTitle = "话费充值订单";
                break;
            case PAY_TYPE_PRODUCT:
                handle_notify = "handle_zd_notify";
                tempTitle = "购买终端订单";
                break;
            default:
                break;

        }
        if (TextUtils.isEmpty(title)) {
            title = tempTitle;
        }
        txtMonyDes.setText(title);

        bindJiFenData();
    }

    private void bindJiFenData() {
        showProgressDialog("正在获取订单信息...");
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mPresenter.loadOrderJiFenInfo(orderID, String.valueOf(payType));
            }
        }, 200);
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @OnClick({R.id.btn_pay, R.id.lay_wechatpay})
    public void onViewClicked(View view) {
        // 确认支付
        if (view.getId() == R.id.btn_pay) {

            if (TextUtils.isEmpty(orderID)) {
                showSystemToast("订单号有误！");
                return;
            }
            if (price <= 0) {
                showSystemToast("支付金额不能为零！");
                return;
            }

            showProgressDialog("正在启动微信...");
            mPresenter.createWechatPayOrder(orderID, String.valueOf(price), "通讯100支付订单", handle_notify, use_point, String.valueOf(payType));

        } else if (view.getId() == R.id.lay_wechatpay) {

        }
    }

    /**
     * 微信支付
     *
     * @param pay_param 支付服务生成的支付参数
     */
    private void doWXPay(final String pay_param) {
        //替换为自己的appid
        String wx_appid = "wx686563a7ca0bcfd5";
        //要在支付前调用
        WXPay.init(getApplicationContext(), wx_appid);
        WXPay.getInstance().doPay(pay_param, new WXPay.WXPayResultCallBack() {
            @Override
            public void onSuccess() {
                EventBus.getDefault().post(new RefreshOrder());
                Intent intent = new Intent();
                intent.setClass(PayActivity.this, PaySuccessActivity.class);
                intent.putExtra(PaySuccessActivity.INTENT_TYPE, PaySuccessActivity.TYPE_PAY_SUCCESS);
                startActivity(intent);
                finish();
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:
                        Toast.makeText(getApplication(), "未安装微信或微信版本过低", Toast.LENGTH_SHORT).show();
                        break;
                    case WXPay.ERROR_PAY_PARAM:
                        Toast.makeText(getApplication(), "支付失败", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY:
                        Toast.makeText(getApplication(), "支付失败", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplication(), "支付取消", Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    protected void onDestroy() {
        dismissProgressDialog();
        super.onDestroy();
    }

    @Override
    public void loadOrderJiFenResult(JiFenParser jiFenInfo) {
        dismissProgressDialog();
        jifenParser = jiFenInfo;
        if (jifenParser == null || jifenParser.getData() == null || jifenParser.getData().getOrderinfo() == null) {
            showDialog(null,"订单信息无法获取！");
        }
        payType = Integer.parseInt(jifenParser.getData().getOrderinfo().getType());
        orderID = jifenParser.getData().getOrderinfo().getOrder_sn();
        price = Float.parseFloat(jifenParser.getData().getOrderinfo().getPrice());
        bindViewData();
    }

    @Override
    public void loadOrderJiFenError() {
        dismissProgressDialog();
        showDialog(null, getString(R.string.connect_service_error));
    }

    @Override
    public void createWechatPayOrderResult(String result) {
        try {
            if (activityIsDestory()) {
                return;
            }
                      /*  WXPayParamParser payParamParser = JSON.parseObject(result, WXPayParamParser.class);
                        if (payParamParser.getCode() != 200) {
                            dismissProgressDialog();
                            showInfoToast("调用微信失败，参数错误！");
                            return;
                        }
                        StringBuffer sb = new StringBuffer();
                        sb.append("{");
                        sb.append("\"appid\":\"" + payParamParser.getData().getAppId() + "\",");
                        sb.append("\"partnerid\":\"" + payParamParser.getData().getPartnerId() + "\",");
                        sb.append("\"prepayid\":\"" + payParamParser.getData().getPrepayId() + "\",");
                        sb.append("\"package\":\"" + payParamParser.getData().getApppackage() + "\",");
                        sb.append("\"noncestr\":\"" + payParamParser.getData().getNonceStr() + "\",");
                        sb.append("\"timestamp\":\"" + payParamParser.getData().getTimeStamp() + "\",");
                        sb.append("\"sign\":\"" + payParamParser.getData().getSign() + "\"");

                        sb.append("}");
                        */
            // Log.i(TAG, "支付参数:" + sb.toString());

            dismissProgressDialog();
            JSONObject jsonObject = new JSONObject(result);
            if ("200".equals(jsonObject.optString("code"))) {
                doWXPay(jsonObject.optString("data"));
            } else if ("300".equals(jsonObject.optString("code"))) {
                EventBus.getDefault().post(new RefreshOrder());
                Intent intent = new Intent();
                intent.setClass(PayActivity.this, PaySuccessActivity.class);
                intent.putExtra(PaySuccessActivity.INTENT_TYPE, PaySuccessActivity.TYPE_PAY_SUCCESS);
                startActivity(intent);
                finish();
            } else {
                showDialog(null, jsonObject.optString("msg"));
            }
        } catch (Exception ex) {
            dismissProgressDialog();
            showSystemToast("调用微信失败，参数错误！");
            return;
        }
    }

    @Override
    public void createWechatPayOrderError() {
        dismissProgressDialog();
        showDialog(null,getString(R.string.connect_service_error));
    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {

    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return PayMainPrecenter.create();
    }
}
